package com.dru.drutils.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageButton;

import com.dru.drutils.R;

public class DrUtilsImageButton extends ImageButton
{
	private Drawable _pressedDrawable	= null;
	private Drawable _normalDrawable	= null;
	
	public DrUtilsImageButton( Context context )
	{
		super( context );
	}
	
	public DrUtilsImageButton( Context context, AttributeSet attrs )
	{
		super( context, attrs );
		
		TypedArray	typedArray		= context.obtainStyledAttributes( attrs, R.styleable.DrUtilsImageButton );
		String		pressedImage	= typedArray.getString( R.styleable.DrUtilsImageButton_pressedImage );
		
		if( ( pressedImage != null ) && ( pressedImage.length() > 0 ) )
		{
			String[]	pathComponents		= pressedImage.split( "/" );
			String[]	filenameComponents	= pathComponents[2].split( "\\." );
			int			identifier			= getResources().getIdentifier( filenameComponents[0], pathComponents[1], context.getPackageName() );
			
			if( identifier != 0 )
			{
				_pressedDrawable	= context.getResources().getDrawable( identifier );
				_normalDrawable		= getDrawable();
			}
		}
	}
	
	public DrUtilsImageButton( Context context, AttributeSet attrs, int defStyle )
	{
		super( context, attrs, defStyle );
	}
	
	@Override
	public void setSelected( boolean selected )
	{
		super.setSelected( selected );
		
		if( _pressedDrawable != null )
		{
			if( selected == true )
				setImageDrawable( _pressedDrawable );
			else
				setImageDrawable( _normalDrawable );
		}
	}
	
	public void setNormalDrawable ( Drawable drawable )
	{
		_normalDrawable = drawable;
	}
		
	public void setPressedDrawable( Drawable drawable )
	{
		_pressedDrawable = drawable;
	}
	
	@Override
	public boolean onTouchEvent( MotionEvent event )
	{
		if( _pressedDrawable != null )
		{
			if( event.getAction() == MotionEvent.ACTION_DOWN )
				setImageDrawable( _pressedDrawable );
			else if( event.getAction() == MotionEvent.ACTION_UP )
				setImageDrawable( _normalDrawable );
		}
		
		return super.onTouchEvent( event );
	}
}
